package cn.krui.project.pubsub.article;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import cn.krui.helper.pub_sub.SubThread;

/**
 * @author: zc
 * email: zc8023zs@163.com
 * create_time: 2020/6/11 16:41:27
 * article 模块消息订阅者
 */
public class SubThreadArticle extends SubThread {
    private static final Logger logger = LoggerFactory.getLogger(SubThreadArticle.class);
    private JedisPool jedisPool;
    private Jedis jedis;
    private SubscriberArticle subscriberArticle = new SubscriberArticle();
    /**
     * 消息频道
     */
    private final String channel = "article_channel";
    //redis连接地址
    private String spring_redis_host;
    //redis端口
    private int spring_redis_port;
    //redis超时
    private int spring_redis_timeout;
    //redis连接密码
    private String spring_redis_password;

    public SubThreadArticle(String spring_redis_host, int spring_redis_port, int spring_redis_timeout,
            String spring_redis_password) {
        this.spring_redis_host = spring_redis_host;
        this.spring_redis_port = spring_redis_port;
        this.spring_redis_timeout = spring_redis_timeout;
        this.spring_redis_password = spring_redis_password;
    }

    @Override
    public void run() {
        try {
            if (StringUtils.isEmpty(spring_redis_password)) {
                this.jedisPool = new JedisPool(new JedisPoolConfig(), spring_redis_host, spring_redis_port,
                        spring_redis_timeout);
            } else {
                this.jedisPool = new JedisPool(new JedisPoolConfig(), spring_redis_host, spring_redis_port,
                        spring_redis_timeout, spring_redis_password);
            }
            logger.info(String.format("article模块消息订阅者, 频道 %s, 线程将会被阻塞", channel));
            jedis = jedisPool.getResource(); // 取出一个连接
            jedis.subscribe(subscriberArticle, channel); // 通过subscribe 的api去订阅，入参是订阅者和频道名
            jedisPool.close();
            jedis.close();
        } catch (Exception e) {
            logger.error(String.format("%s", e));
            if (jedisPool != null){
                jedisPool.close();
			}
            if (jedis != null){
                jedis.close();
			}
            super.interrupt();
        }
    }

    @Override
    public void destroy() {
        this.jedisPool.close();
        this.jedis.close();
        super.interrupt();
    }

}